package com.crm.service;

import com.crm.entity.Product;
import com.crm.repository.ProductRepository;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.ArrayList;
import java.util.List;

@Service("productService")
public class ProductServiceImpl implements ProductService {

    @Resource
    ProductRepository productRepository;

    @Override
    public Page<Product> findAllByPage(Pageable pageable, String prodName, String prodType, String prodBatch) {
        Specification<Product> specification = new Specification<Product>() {
            @Override
            public Predicate toPredicate(Root<Product> root, CriteriaQuery<?> query, CriteriaBuilder criteriaBuilder) {
                List<Predicate> predicates = new ArrayList<>();
                if (prodName != null && !prodName.equals("")) {
                    predicates.add(criteriaBuilder.like(root.get("prodName"), "%" + prodName + "%"));
                }
                if (prodType != null && !prodType.equals("")) {
                    predicates.add(criteriaBuilder.like(root.get("prodType"), "%" + prodType + "%"));
                }
                if (prodBatch != null && !prodBatch.equals("")) {
                    predicates.add(criteriaBuilder.like(root.get("prodBatch"), "%" + prodBatch + "%"));
                }
                return criteriaBuilder.and(predicates.toArray(new Predicate[predicates.size()]));
            }
        };
        return productRepository.findAll(specification,pageable);
    }
}
